#!/bin/bash
#
# This script compress and upload the built static wallet core common xcframework to github release
#

set -o pipefail
set -e

# load release library code
base_dir=$(cd `dirname $0`; pwd)

source ${base_dir}/library
src_dir=${base_dir}/..
built_dir=${base_dir}/../build/ios-frameworks

# version to release
version=$(wc_read_version $1)
echo "release version ${version}"

pushd ${built_dir}
# archive headers, swift code and xcframework

rm -rf release && mkdir -p release

cp -R WalletCoreCommon.xcframework release
cp -R ${src_dir}/include release
cp -R ${src_dir}/swift/Sources release
rm release/Sources/Dummy.cpp
cp ${src_dir}/License release

filename="TrustWalletCore-${version}.tar.xz"
pushd release
tar -cJvf ../${filename} .
popd

# upload to release
echo "Upload asset $filename"
download_url=$(wc_upload_asset ${version} ${filename})
echo "download_url is $download_url"
download_url=$(tr -d '"' <<< $download_url)
echo "trimmed download_url is ${download_url}"

# create podspec
podspec_name=TrustWalletCore
podspec=${podspec_name}.podspec
cat > $podspec <<EOF 
Pod::Spec.new do |s|
  s.name         = '${podspec_name}'
  s.version      = '${version}'
  s.summary      = 'Trust Wallet core data structures and algorithms.'
  s.homepage     = 'https://github.com/trustwallet/wallet-core'
  s.license      = 'MIT'
  s.authors      = { 'Alejandro Isaza' => 'al@isaza.ca' }
  s.module_name  = 'WalletCore'
  s.ios.deployment_target = '12.0'
  s.osx.deployment_target = '10.14'
  s.swift_version = '5.1'
  s.source = {
    http: '${download_url}'
  }
  s.default_subspec = 'Core'
  s.subspec 'Types' do |ss|
    ss.source_files = 
      'Sources/Types/*.swift',
      'Sources/Generated/Enums/*.swift',
      'Sources/Generated/Protobuf/*.swift'
    ss.dependency 'WalletCoreSwiftProtobuf'
  end
  s.subspec 'Core' do |ss|
    ss.vendored_frameworks = '*.xcframework'
    ss.exclude_files = 'Sources/Generated/WalletCore.h'
    ss.source_files =
      'include/**/*.h',
      'Sources/*.{swift,h,m,cpp}',
      'Sources/Extensions/*.swift',
      'Sources/Generated/*.{swift,h}'
    ss.public_header_files =
      'include/**/*.h',
      'Sources/*.h'
    ss.libraries = 'c++'
    ss.dependency 'TrustWalletCore/Types'
  end
end
EOF

echo "generated podspec: "
cat ${podspec}

# pod trunk push
echo "Done. running: pod trunk push --allow-warnings ${podspec}"

pod trunk push --verbose --allow-warnings ${podspec}

popd
